import { getRouteByKey, ROUTE_CONFIG, ROUTE_KEY, routes } from "@/routes/menus";
import { useEffect, useMemo } from "react";
import { matchPath, useLocation, useNavigate } from "react-router-dom";

export const useTitle = (title: string) => {
  useEffect(() => {
    document.title = title;
  }, [title]);
};

/**
 * 通用页面跳转器
 * @returns
 */
export const useGoTo = () => {
  const nav = useNavigate();
  const back = () => nav(-1);
  const go = (pageKey?: string, params?: Record<string, string | number>) => {
    if (!pageKey) {
      nav("/home");
      return;
    }
    const route = getRouteByKey(pageKey);
    if (route && route.path) {
      if (!params) {
        nav(`/${route.path}`);
        return;
      } else {
        // 传入参数为  /page/:id   params:{id:134}
        // 应该返回 /page/134
        const url = route.path.replace(
          /\/:(\w+)/g,
          (_exp: string, exp1: string) => {
            return `/${params?.[exp1]}/`;
          }
        );
        nav(`/${url}`);
      }
    }
  };
  return { go, back };
};

/**
 * 获取当前匹配的路由
 * @returns
 */
export const  useMatchedRoute=()=> {
  const r = useLocation();
  
  const route = useMemo(() => {
    return routes.find((item) => {
      return matchPath(`/${item.path}`, r.pathname);
    });
  }, [r.pathname]);

  return route;
};

export const useIsOrgRoute:()=>boolean = ()=>{
  const curRoot = useMatchedRoute()
  if(curRoot?.path === ROUTE_CONFIG[ROUTE_KEY.ORG].path)
    return true
  return false
}
